package cn.wanho.securityuser;


import cn.wanho.config.MyCustomerPasswordEncoder;
import cn.wanho.dao.CmsMenuAuthorityMapper;
import cn.wanho.dao.CmsUserMapper;
import cn.wanho.dto.CmsMenuAuthority;
import cn.wanho.dto.CmsUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private MyCustomerPasswordEncoder myCustomerPasswordEncoder;
    @Resource
    private CmsMenuAuthorityMapper cmsMenuAuthorityMapper;
    @Resource
    CmsUserMapper cmsUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(username == null || "".equals(username)){
            throw new RuntimeException("用户名不能为空");
        }
        CmsUser cmsUser = cmsUserMapper.selectByUsername(username);
        //定义权限集合
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        /**
         * 如果用户存在，获取他权限集合
         */
        if (cmsUser != null){
            List<CmsMenuAuthority> cmsMenuAuthorities = cmsMenuAuthorityMapper.selectByUsername(username);
            for (CmsMenuAuthority cmsMenuAuthority : cmsMenuAuthorities) {
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(cmsMenuAuthority.getAuthorityFlag());
                grantedAuthorities.add(simpleGrantedAuthority);
            }
        }else{
            throw new RuntimeException("用户不存在");
        }
       return new User(cmsUser.getUsername(),cmsUser.getPassword(),true,true,true,true,grantedAuthorities);
    }
}
